package com.snailhd.framework.i18n.nacos;

import com.snailhd.framework.i18n.nacos.file.parse.AbstractFileParser;
import com.snailhd.framework.i18n.nacos.file.parse.PropertiesFileParser;
import com.snailhd.framework.i18n.nacos.file.parse.YamlFileParser;

import java.util.HashMap;
import java.util.Map;

/**
 * @author snailhd
 */
public class FileParserFactory {

    private static final Map<String,Class<? extends AbstractFileParser>> mapping = new HashMap<String,Class<? extends AbstractFileParser>>(){{
        put(".properties", PropertiesFileParser.class);
        put(".yml", YamlFileParser.class);
        put(".yaml", YamlFileParser.class);
    }};

    public static FileParser factory(String sourceDataId, String locale){

        int lastSpot = sourceDataId.lastIndexOf(".");
        if(lastSpot==-1){
            return null;
        }
        String format = sourceDataId.substring(lastSpot);
        sourceDataId = sourceDataId.substring(0, lastSpot);

        if(!mapping.containsKey(format)){
            return null;
        }
        Class<? extends AbstractFileParser> aClass = mapping.get(format);
        try {
            AbstractFileParser fileParseHandler = aClass.newInstance();

            fileParseHandler.setFormat(format);
            String dataId = sourceDataId +
                    "_" + locale +
                    format;
            fileParseHandler.setDataId(dataId);
            return fileParseHandler;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

}
